package com.study_security.utils;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import org.springframework.stereotype.Component;

@Component
public class SmsUtils {

    private final Client client;

    public SmsUtils() throws Exception {
        Config config = new Config()
                .setAccessKeyId("LTAI5tJpYeVwxdkpnifa9aoi")
                .setAccessKeySecret("Uib0gI37siVaiSZm6qT4B1lSeGlwgt");

        config.endpoint = "dysmsapi.aliyuncs.com";
        this.client = new Client(config);
    }

    public void sendSms(String signName, String templateCode, String phoneNumbers, String templateParam) throws Exception {
        com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                .setSignName(signName)
                .setTemplateCode(templateCode)
                .setPhoneNumbers(phoneNumbers)
                .setTemplateParam(templateParam);

        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            client.sendSmsWithOptions(sendSmsRequest, runtime);
        } catch (TeaException error) {
            // 打印错误信息
            System.out.println("SMS发送失败: " + error.getMessage());
            throw error;
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            System.out.println("SMS发送失败: " + error.getMessage());
            throw error;
        }
    }
}
